<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        mode="horizontal"
        :selected-keys="selectKeys"
        @menu-item-click="doMenuClick"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '38px' }"
          disabled
        >
          <div class="title-bar">
            <img src="../assets/logo.png" alt="OJ" class="logo" />
            <div class="title">OJ</div>
          </div>
        </a-menu-item>
        <a-menu-item v-for="item in visibleRoutes" :key="item.path">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-col>
    <a-col flex="100px">
      <a-tooltip :content="tip">
        <a-avatar
          :style="{
            marginRight: '24px',
            verticalAlign: 'middle',
            backgroundColor: '#3370ff',
          }"
          @click="doAvatarClick"
          style="cursor: default"
        >
          {{ store.state.user?.loginUser?.userName ?? "未登录" }}
        </a-avatar>
      </a-tooltip>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { routes } from "@/router/routes";
//点击导航栏，跳转不同页面
import { useRouter } from "vue-router";
import { computed, ref } from "vue";
import { useStore } from "vuex";
import checkAccess from "@/access/checkAccess";
import ACCESS_ENUM from "@/access/accessEnum";

const router = useRouter();
let tip = "登录以使用完整功能";

//获取当前登录用户名
const store = useStore();

// setTimeout(() => {
//   store.dispatch("user/getLoginUser", {
//     userName: "CWT",
//     userRole: ACCESS_ENUM.ADMIN,
//   });
// }, 3000);

// 展示与不展示菜单
const visibleRoutes = computed(() => {
  return routes.filter((item, index) => {
    if (item.meta?.hideInMenu) {
      return false;
    }
    //动态计算属性值  值发生改变，组件重新渲染
    return checkAccess(store.state.user.loginUser, item.meta?.access as string);
  });
});

// const doToolTipVisible = () => {
//   return store.state.user.loginUser.userRole === ACCESS_ENUM.NOT_LOGIN;
// };

const doAvatarClick = () => {
  if (
    !store.state.user.loginUser.userRole ||
    store.state.user.loginUser.userRole === ACCESS_ENUM.NOT_LOGIN
  ) {
    tip = "登录以使用完整功能";
    router.push({
      path: "/user/login",
      replace: true,
    });
  } else {
    tip = "用户注销";
    router.push({
      path: "/user/loginOut",
      replace: true,
    });
  }
};

const doMenuClick = (key: string) => {
  router.push({
    path: key,
  });
};

//默认主页
const selectKeys = ref(["/"]);

//路由跳转后，导航栏高亮也随之变化
router.afterEach((to, from, failure) => {
  selectKeys.value = [to.path];
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: #444;
  margin-left: 14px;
}

.logo {
  height: 60px;
}
</style>
